package org.inspursc.s0517.health.common.controller;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.inspursc.s0517.health.common.converter.UserConverter2SysUserDTO;
import org.inspursc.s0517.health.common.dto.SysUserDTO;
import org.inspursc.s0517.health.common.entity.SysUser;
import org.inspursc.s0517.health.common.enums.ResultEnum;
import org.inspursc.s0517.health.common.exception.BizException;
import org.inspursc.s0517.health.common.form.UserForm;
import org.inspursc.s0517.health.common.service.SysUserService;
import org.inspursc.s0517.health.common.util.ResponseUtil;
import org.inspursc.s0517.health.common.vo.PageVO;
import org.inspursc.s0517.health.common.vo.ResponseVO;
import org.inspursc.s0517.health.common.vo.SysUserVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.http.ResponseEntity;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;

@RestController
@RequestMapping(value = "/api/user")
@Slf4j
@Api(value = "系统用户的Controller")
public class SysUserController {

    @Autowired
    private SysUserService userService;

    @Autowired
    private PasswordEncoder passwordEncoder;

    @ApiOperation(value = "保存用户信息")
    @PostMapping("/save")
    public ResponseEntity<ResponseVO> save(@ApiParam("用户表单参数") @Valid UserForm userForm, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            throw new BizException(ResultEnum.PARAM_ERROR.getCode(), bindingResult.getFieldError().getDefaultMessage());
        }
        SysUserDTO sysUserDTO = UserConverter2SysUserDTO.converter(userForm);
        SysUserVO user;
        if(userForm.getId()==null) {
           user = userService.findByUserName(sysUserDTO.getUsername());
            if(user==null) {
                SysUserDTO userDTO = userService.save(sysUserDTO, userForm.getRoleIds());
                if (null != userDTO) {
                    return ResponseUtil.success("保存成功", userDTO);
                }else {
                    return ResponseUtil.error("保存失败", userDTO);
                }
            }else {
                return ResponseUtil.error("已存在相同账号",false);
            }
        }else {
            SysUserDTO userDTO = userService.save(sysUserDTO, userForm.getRoleIds());
            if (null != userDTO) {
                return ResponseUtil.success("修改成功", userDTO);
            }else {
                return ResponseUtil.error("修改失败", userDTO);
            }
        }

    }

    @ApiOperation(value = "根据用户ID，删除用户信息")
    @GetMapping("/delete/{id}")
    public ResponseEntity<ResponseVO> delete(@ApiParam(value = "用户ID", required = true) @PathVariable Integer id) {
        boolean is = userService.deleteById(id);
        if (is) {
            return ResponseUtil.success("删除成功", is);
        }
        return ResponseUtil.error("删除失败", is);
    }


    @ApiOperation(value = "根据用户ID，获取用户信息")
    @GetMapping("/get/{id}")
    public ResponseEntity<ResponseVO> get(@ApiParam(value = "用户ID", required = true) @PathVariable Integer id) {
        SysUserVO userVO = userService.findById(id);
        if (null != userVO) {
            return ResponseUtil.success("", userVO);
        }
        return ResponseUtil.error("用户信息为空", "");
    }


    @ApiOperation(value = "根据查询条件，查询用户信息，并分页显示")
    @PostMapping(value = "/getByPage")
    public ResponseEntity<ResponseVO> getAll(@ApiParam(value = "用户名", required = false) @RequestParam String username,
                             @ApiParam(value = "当前页数", required = true) @RequestParam Integer pageIndex,
                             @ApiParam(value = "每页显示条数", required = true) @RequestParam Integer pageSize) {
        Pageable pageable = PageRequest.of(pageIndex - 1, pageSize);
        Page<SysUser> page = userService.findByUserNameLike(username, pageable);
        List<SysUserVO> sysUserVOList = UserConverter2SysUserDTO.converter2VO(page.getContent());
        PageVO pageVO = new PageVO(sysUserVOList, page.getTotalPages(), page.getTotalElements(), pageIndex);
        return ResponseUtil.success("", pageVO);
    }

    @ApiOperation(value = "根据角色Id，获取有该角色的用户")
    @GetMapping(value = "/getUserByRoleId")
    public ResponseEntity<ResponseVO> getUserByRoleId(@ApiParam(value = "角色ID") @RequestParam Integer roleId) {
        List<SysUserVO> sysUserVOList = userService.findByRoleId(roleId);
        return ResponseUtil.success("", sysUserVOList);
    }

    @ApiOperation(value = "用户密码修改")
    @PostMapping(value = "/updatePassword")
    public ResponseEntity<ResponseVO> updatePassword(@ApiParam(value = "用户ID") @RequestParam Integer id,
                                     @ApiParam(value = "旧密码") @RequestParam String oldPwd,
                                     @ApiParam(value = "密码") @RequestParam String password) {
        SysUser sysUser = userService.findByUId(id);
        if (passwordEncoder.matches(oldPwd, sysUser.getPassword())) {
            sysUser.setPassword(passwordEncoder.encode(password));
            SysUserDTO sysUserDTO = UserConverter2SysUserDTO.converter(sysUser);
            if (null != userService.save(sysUserDTO, null)) {
                return ResponseUtil.success("密码修改成功", null);
            }
        } else {
            return ResponseUtil.error("原始密码不正确!", null);
        }
        return ResponseUtil.error("密码修改失败", null);
    }

    @ApiOperation(value = "重置用户密码")
    @PostMapping(value = "/resetPassword")
    public ResponseEntity<ResponseVO> updatePassword(
            @ApiParam(value = "用户ID") @RequestParam Integer id,
            @ApiParam(value = "密码") @RequestParam String password) {
        SysUser sysUser = userService.findByUId(id);
        sysUser.setPassword(passwordEncoder.encode(password));
        SysUserDTO sysUserDTO = UserConverter2SysUserDTO.converter(sysUser);
        if (null != userService.save(sysUserDTO, null)) {
            return ResponseUtil.success("重置密码成功", null);
        }

        return ResponseUtil.error("重置密码失败", null);
    }
}
